package com.xianggu.register;

import com.alibaba.fastjson2.JSON;
import com.xianggu.protocol.URL;
import com.xianggu.redis.RedisConnection;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chengjy
 * @date 2025/3/9
 */
public class RedisLocalRegister {
    public static RedisConnection redis = new RedisConnection("192.168.80.130", 6379);
    public static void main(String[] args) {
        register("Provider", "localhost", 8080);
        List<URL> provider = getRegister("Provider");
        System.out.println(provider);
    }

    private static String localKey = "XiangGu:LocalRegister:";
    public static void register(String serviceName, String hostName, Integer prot){
        String url = hostName + ":" + prot;
        List<String> urls = new ArrayList<>();
        urls.add(url);


        String key = localKey + serviceName;
        // 判断服务是否存在
        if (redis.exists(key)) {
            String urlJson = redis.get(key);
            // 判断是否已经存在
            List<String> oldUrl = (List<String>) JSON.parse(urlJson);
            if (oldUrl.contains(url)) {
                return;
            }else{
                urls.addAll(oldUrl);
            }
        }
        redis.set(key, JSON.toJSONString(urls));
    }

    public static List<URL> getRegister(String serviceName) {
        String key = localKey + serviceName;

        String urlJson = redis.get(key);
        List<String> oldUrl = (List<String>) JSON.parse(urlJson);

        // 转换成URL集合返回
        List<URL> urls = oldUrl.stream().map(
                url -> {
                    String[] split = url.split(":");
                    return new URL(split[0], Integer.parseInt(split[1]));
                }
        ).collect(Collectors.toList());
        return urls;
    }
}
